let socket = null;
let onMessageCallbacks = [];
let onStatusCallback = null;
let reconnectTimer = null;
let lastConnectParams = null;
let lastMessage = null; // 存储上一条消息用于去重

export function connectChatSocket({ expertId, userId, role, onMessage, onStatus }) {
    if (onMessage && !onMessageCallbacks.includes(onMessage)) {
        onMessageCallbacks.push(onMessage);
    }
    onStatusCallback = onStatus;
    lastConnectParams = { expertId, userId, role };
    if (socket) return; // 已连接
    const wsUrl = `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.hostname}:1234/ws/chat?userId=${userId || ''}&expertId=${expertId || ''}&role=${role}`;
    socket = new WebSocket(wsUrl);
    socket.onopen = () => {
        if (onStatusCallback) onStatusCallback('open');
    };
    socket.onmessage = (event) => {
        console.log('WebSocket 收到消息', event.data);
        const msg = JSON.parse(event.data);

        // 去重逻辑：只有当消息内容与上一条不同时才回调
        if (!lastMessage || JSON.stringify(msg) !== JSON.stringify(lastMessage)) {
            onMessageCallbacks.forEach(cb => {
                console.log('调用回调', cb);
                cb && cb(msg);
            });
            lastMessage = msg; // 更新最后一条消息
        } else {
            console.log('收到重复消息，已忽略');
        }
    };
    socket.onerror = (e) => {
        if (onStatusCallback) onStatusCallback('error', e);
    };
    socket.onclose = () => {
        if (onStatusCallback) onStatusCallback('close');
        socket = null;
        reconnectTimer = setTimeout(() => {
            if (lastConnectParams) connectChatSocket(lastConnectParams);
        }, 3000);
    };
}

export function sendChatMessage(msg) {
    if (socket && socket.readyState === 1) {
        socket.send(JSON.stringify(msg));
    }
}

export function closeChatSocket() {
    if (reconnectTimer) clearTimeout(reconnectTimer);
    if (socket) {
        socket.close();
        socket = null;
    }
    onMessageCallbacks = [];
} 